package com.yemast.bluetoothtest

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.reflect.Field
import java.lang.reflect.InvocationTargetException
import java.net.NetworkInterface
import java.util.*


class MainActivity : AppCompatActivity() {
    val REQUESTCODE_BLUETOOTH_ENABLECODE = 101

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        val defaultAdapter = BluetoothAdapter.getDefaultAdapter()
        if (defaultAdapter == null) {
            Log.e("tag", "不支持蓝牙");
            return
        }

        if (!defaultAdapter.isEnabled) {
            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(intent, REQUESTCODE_BLUETOOTH_ENABLECODE)//开启蓝牙
        }
        button.setOnClickListener {
            scan4()



        }


        button2.setOnClickListener {
            scanlte()
        }

    }

    var scancallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            super.onScanResult(callbackType, result)
            result?.run {
                val device = this.device
                Log.e("tag", "device==${device.address},devicename==${device.name}");
            }
            Log.e("tag", "callbackType==$callbackType");

        }


        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            Log.e("tag", "errorCode==$errorCode");
        }

    }


    fun scan4() {
        var btm = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val adapter = btm.adapter
        val bluetoothLeScanner = adapter.bluetoothLeScanner
        bluetoothLeScanner.startScan(scancallback)

        Handler().postDelayed({
            Log.e("tag", "停止监听");
            bluetoothLeScanner.stopScan(scancallback)
        }, 10 * 1000)
    }

    //经典蓝牙
    fun scanlte() {
        getWifiMacAddress()

        getBluetoothMacAddress()
        val adapter = BluetoothAdapter.getDefaultAdapter()
        adapter.startDiscovery()
        Handler().postDelayed({
            adapter.cancelDiscovery()
        }, 10 * 1000)
    }


    private fun getWifiMacAddress(): String {
        val defaultMac = "02:00:00:00:00:00"
        try {
            val interfaces: List<NetworkInterface> = Collections
                .list(NetworkInterface.getNetworkInterfaces())
            for (ntwInterface in interfaces) {
                if (ntwInterface.name ==("wlan0")) {//之前是p2p0，修正为wlan
                    val byteMac: ByteArray = ntwInterface.getHardwareAddress()
                    if (byteMac == null) {
                        // return null;

                    }
                    val strBuilder = StringBuilder()
                    for (i in byteMac.indices) {
                        strBuilder.append(String.format("%02X:", byteMac[i]))
                    }
                    if (strBuilder.length > 0) {
                        strBuilder.deleteCharAt(strBuilder.length - 1)
                    }
                    return strBuilder.toString()
                }
            }
        } catch (e: Exception) {
//             Log.d(TAG, e.getMessage());
            Log.e("tag", "");

        }
        return defaultMac
    }


    private fun getBluetoothMacAddress(): String {
        val bluetoothAdapter: BluetoothAdapter =
            BluetoothAdapter.getDefaultAdapter()
        var bluetoothMacAddress = ""
        try {
            val mServiceField: Field = bluetoothAdapter.javaClass.getDeclaredField("mService")
            mServiceField.setAccessible(true)
            val btManagerService: Any = mServiceField.get(bluetoothAdapter)
            if (btManagerService != null) {
                bluetoothMacAddress =
                    btManagerService.javaClass.getMethod("getAddress").invoke(btManagerService) as String
            }
        } catch (ignore: NoSuchFieldException) {
            Log.e("", "");
        } catch (ignore: NoSuchMethodException) {
            Log.e("", "");

        } catch (ignore: IllegalAccessException) {
            Log.e("", "");

        } catch (ignore: InvocationTargetException) {
            Log.e("", "");

        }
        return bluetoothMacAddress
    }

}
